package com.rui.study.micro.userself.util;

import com.rui.study.commons.model.BizException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2018-11-20 14:31
 **/
@Service
public class RedisLock {

    @Resource(name = "redisTemplate")
    private HashOperations<Serializable, String, Object> HashOps;

    public boolean lock(String method) {
        while (!HashOps.putIfAbsent("SYNC_METHOD", method, "LOCK")){

        }
        HashOps.getOperations().expire(method, 2, TimeUnit.SECONDS);
        return true;
    }

    public void unlock(String method) {
        Long r = HashOps.delete("SYNC_METHOD", method);
        if (r != 1)
            throw new BizException(StatusCode.RELEASE_LOCK_FAILED, method);
    }
}
